package org.leonos.utils;

import org.leonos.core.common.Const;
import org.leonos.web.system.model.Menu;
import org.leonos.web.system.model.User;

import java.util.List;

/**
 * 页面内容生成器
 * @author LeonXiao
 */
public class PageCreator {

    /**
     * 根据用户所拥有的权限生成左部菜单
     * @param user
     *              用户
     * @return menu
     */
    public static String createToolMenuByUser(User user) {

        List<Menu> menus = findMenusByUser(user);

        StringBuilder strBuilder = new StringBuilder();
        for (Menu m : menus) {
            String menu = createMenuByUserAndPid(user, m.getStr("id"));
            if (Utils.isNull(menu)) {
                strBuilder.append("<li><a href=\"javascript:void(0)\" onclick=\"goToUrl('").append(m.getStr("requesturl")).append("')\">");
                strBuilder.append("<i class=\"lnr ").append(m.getStr("micon")).append("\"></i>");
                strBuilder.append(" <span>").append(m.getStr("name")).append("</span></a></li>");
                continue;
            }

            strBuilder.append("<li><a href=\"#").append(m.getStr("id")).append("\" data-toggle=\"collapse\" class=\"collapsed\">");
            strBuilder.append("<i class=\"lnr ").append(m.getStr("micon")).append("\"></i> <span>").append(m.getStr("name")).append("</span>");
            strBuilder.append("<i class=\"icon-submenu lnr lnr-chevron-left\"></i></a>");
            strBuilder.append("<div id=\"").append(m.getStr("id")).append("\" class=\"collapse\">");
            strBuilder.append("<ul class=\"nav\">");
            strBuilder.append(menu);
            strBuilder.append("</ul></div></li>");
        }
        return strBuilder.toString();
    }

    /**
     * 生成菜单（递规找到子菜单）
     * @param user
     *              用户
     * @param pid
     *              父级菜单id
     * @return menu
     */
    private static String createMenuByUserAndPid(User user, String pid) {

        List<Menu> menus = findMenusByUserAndPid(user, pid);

        StringBuilder strBuilder = new StringBuilder();
        if (menus.size() > 0) { // 表示有子菜单(ul)
            for (Menu m : menus) {
                if (!containSubMenu(m.getStr("id"))) {
                    strBuilder.append("<li><a href=\"javascript:void(0)\" onclick=\"goToUrl('").append(m.getStr("requesturl")).append("')\">").append(m.getStr("name")).append("</a></li>");
                    continue;
                }
                strBuilder.append("<li><a href=\"#").append(m.getStr("id")).append("\" data-toggle=\"collapse\" class=\"collapsed\">");
                strBuilder.append("<i class=\"lnr ").append(m.getStr("micon")).append("\"></i> <span>").append(m.getStr("name")).append("</span> </a>");
                strBuilder.append("<i class=\"icon-submenu lnr lnr-chevron-left\"></i>");
                strBuilder.append("<div id=\"").append(m.getStr("id")).append("\" class=\"collapse\">");
                strBuilder.append("<ul class=\"nav\">");
                String menu = createMenuByUserAndPid(user, m.getStr("id"));
                strBuilder.append(menu);
                strBuilder.append("</ul></div></li>");
            }
        }
        return strBuilder.toString();
    }

    /**
     * 检测是否包含子菜单
     * @param pid
     *              父级菜单id
     * @return boolean
     */
    private static boolean containSubMenu(String pid) {
        return Menu.dao.findSubMenu(pid).size() != 0;
    }

    /**
     * 根据用户查询相应菜单
     * @param user
     *              用户
     * @return menus
     */
    private static List<Menu> findMenusByUser(User user) {

        List<Menu> menus;
        String uid = user.get("id").toString();
        if (Utils.isCheck(user)) {
            String sql = "select * from sys_menu m INNER JOIN (" +
                    " select m.menuid from sys_user_menu m where m.userid = ?" +
                    " UNION select m.menuid from sys_role_menu m INNER JOIN (" +
                    " select * from sys_user_role r where r.userid = ?" +
                    " ) a on a.roleid = m.roleid" +
                    " UNION select p.menuid from sys_position_menu p INNER JOIN (" +
                    " select * from sys_user u where status = 0 and u.id = ?" +
                    " ) a on a.type = p.positionid)" +
                    " q on m.id = q.menuid where m.status = 0 and mlevel = 2 and " +
                    " pid = (select id from sys_menu where status = 0 and mlevel = 1 and permissions = ?" +
                    " ) order by sort asc";

            Object[] params = new Object[]{uid, uid, uid, Const.MANGE_MENU};
            menus = Menu.dao.find(sql, params); // 所有的根菜单
        } else { // 不用验证
            String sql = "select * from sys_menu where status = 0 and mlevel = 2 and" +
                    " pid = (select id from sys_menu where status = 0 and mlevel = 1 and permissions = ?)" +
                    " order by sort asc";

            menus = Menu.dao.find(sql, Const.MANGE_MENU); // 所有的根菜单
        }

        return menus;
    }

    /**
     * 根据用户和父级菜单id查询相应子菜单
     * @param user
     *              用户
     * @param pid
     *              父级菜单id
     * @return menus
     */
    private static List<Menu> findMenusByUserAndPid(User user, String pid) {
        List<Menu> menus;
        String uid = user.get("id").toString();
        if (Utils.isCheck(user)) {
            String sql = "select * from sys_menu m INNER JOIN (" +
                    " select m.menuid from sys_user_menu m where m.userid = ?" +
                    " UNION select m.menuid from sys_role_menu m INNER JOIN (" +
                    " select * from sys_user_role r where r.userid = ?" +
                    " ) a on a.roleid = m.roleid" +
                    " UNION select p.menuid from sys_position_menu p INNER JOIN (" +
                    " select * from sys_user u where status = 0 and u.id = ?" +
                    " ) a on a.type = p.positionid)" +
                    " q on m.id = q.menuid where m.status = 0 and mlevel = 2" +
                    " and pid = ? order by sort asc";

            Object[] params = new Object[]{uid, uid, uid, pid};
            menus = Menu.dao.find(sql, params); // 所有的链接子菜单(li)
        } else {
            String sql = "select * from sys_menu where status = 0 and mlevel = 2" +
                    " and pid = ? order by sort asc";
            menus = Menu.dao.find(sql, pid); // 所有的子菜单
        }

        return menus;
    }


    /**
     * 根据用户生成菜单列表
     * 使用控件：mtree
     * @param user
     *              用户
     * @return String
     */
    public static String createMenusInPanelByUser(User user) {
        List<Menu> menus = findMenusByUser(user);
        String menusInPanel = (menus.size() == 0 ? "" : createMenusInPanel(user, menus));
        return menusInPanel.equals("") ? "" : menusInPanel.replaceFirst("<ul>", "<ul class=\"mtree bubba\">");
    }

    /**
     * 根据用户和父级菜单id生成子菜单列表
     * @param user
     *              用户
     * @param pid
     *              父级菜单id
     * @return String
     */
    private static String createMenusInPanelByUserAndPid(User user, String pid) {
        List<Menu> menus = findMenusByUserAndPid(user, pid);
        return menus.size() == 0 ? "" : createMenusInPanel(user, menus);
    }

    /**
     * 生成菜单列表
     * @param user
     *              用户
     * @param menus
     *              菜单
     * @return String
     */
    private static String createMenusInPanel(User user, List<Menu> menus) {
        StringBuilder strBuilder = new StringBuilder();
        strBuilder.append("<ul>");
        for (Menu m : menus) {
            strBuilder.append("<li><a id=\"").append(m.getStr("id")).append("\" href=\"javascript:void(0)\" onclick=\"editMenu('").append(m.getStr("id")).append("')\">");
            strBuilder.append(m.getStr("name")).append("</a>");
            strBuilder.append(createMenusInPanelByUserAndPid(user, m.getStr("id")));
            strBuilder.append("</li>");
        }
        strBuilder.append("</ul>");
        return strBuilder.toString();
    }

}
